import { get, post } from '@/axios/http'
import comFunc from '@/common/comFunc'
import { Sysinfo } from '@/common/config'
import { t } from '@/common/locale'

export const queryList = async (
  type: 'train' | 'teach',
  p: {
    categoryId?: string
    name?: string
    orderBy?: string
    status?: string
    timeStatus?: string
    pageSize?: number
    to?: number
  }
): Promise<{
  isSuccess: boolean
  msg: string
  data?: any[]
  pageSize?: number
  pageNum?: number
  totalRow?: number
  totalPages?: number
}> => {
  if (!p.pageSize) p.pageSize = Sysinfo.PageSize
  if (!p.to) p.to = 1
  let url =
    type === 'teach' ? '/project/teach/getTeachByCondition' : '/project/teach/getTrainByCondition'
  const re = await post(url, {
    categoryId: comFunc.nvl(p.categoryId) === '' ? null : p.categoryId,
    name: comFunc.nvl(p.name) === '' ? null : p.name,
    orderBy: comFunc.nvl(p.orderBy) === '' ? null : p.orderBy,
    status: comFunc.nvl(p.status) === '' ? null : p.status,
    timeStatus: comFunc.nvl(p.timeStatus) === '' ? null : p.timeStatus,
    pageNum: p.to,
    pageSize: p.pageSize
  }).catch((err) => {
    return err.response || err
  })
  const data =
    re.data && re.data.data
      ? re.data.data
      : {
          list: [],
          pageSize: Sysinfo.PageSize,
          pageNum: 1,
          totalRow: 0,
          totalPages: 0
        }
  if (re.data) {
    if (re.data.success) {
      return {
        isSuccess: re.data.success,
        msg: re.data.message,
        data: data.list,
        pageSize: data.pageSize > 0 ? data.pageSize : Sysinfo.PageSize,
        pageNum: data.pageNum,
        totalRow: data.total,
        totalPages: data.pages
      }
    } else {
      return {
        isSuccess: re.data.success,
        msg: re.data.message
      }
    }
  } else {
    return {
      isSuccess: false,
      msg: `查询失败:无返回结果`
    }
  }
}
export const deleteBy = async (
  data: TeachDataModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  const re = await get('/project/teach/delTeach?objectId=' + data.objectId).catch(
    (err) => err.response || err
  )
  if (!re)
    return {
      isSuccess: false,
      msg: t('操作失败：服务端操作失败')
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: t('操作失败：服务端未返回结果')
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误'
  }
}
